package com.example.lastwork.service;

import com.example.lastwork.common.service.LogicService;
import com.example.lastwork.dao.CustomerDao;
import com.example.lastwork.dao.OrdersDao;
import com.example.lastwork.dao.ShopDao;
import com.example.lastwork.entity.Customer;
import com.example.lastwork.entity.Orders;
import com.example.lastwork.entity.Shop;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CustomerService extends LogicService<CustomerDao, Customer, Long> {
    @Resource
    private ShopDao shopDao;

    @Resource
    private OrdersDao ordersDao;

    public CustomerService(@Autowired CustomerDao dao){
        super(dao);
    }

    public Orders createNewOrder(Long customerId, Long shopId){
        Customer customer = getDAO().getReferenceById(customerId);
        Shop shop = shopDao.getReferenceById(shopId);
        Orders order = customer.createNewOrder(shopId);
        order.setShop(shop);
        ordersDao.save(order);
        return order;
    }

    public String cancelUnpaidOrder(Long customerId, Long shopId){
        Customer customer = getDAO().getReferenceById(customerId);
        Orders order = customer.cancelUnpaidOrder(shopId);
        if (order == null)
            return "您在本店没有未支付的订单，取消订单失败";
        ordersDao.save(order);
        return "订单取消成功";
    }

    @Transactional
    public String payment(Long ordersId){
        int result = getDAO().payment(ordersId);
        if (result == 1)
            return "支付成功";
        return "支付失败";
    }

    public List<Orders> getOrdersByCustomerId(Long customerId){
        return getDAO().getOrdersByCustomerId(customerId);
    }
}
